﻿using System;
using System.Net;
using System.Windows;
using ControleRepresentante.Common;
using ControleRepresentanteSync.Application.Wizard;
using ControleRepresentanteSync.ControleRepresentanteServices;
using ControleRepresentanteSync.Logic;

namespace ControleRepresentanteSync.Application.Setup
{
    internal class UserPagePresenter : WizardPagePresenterBase<IUserPageViewModel>
    {
        private readonly IWindow m_Window;
        private readonly ConfigurationInfo m_ConfigurationInfo;
        private readonly IUserInterfaceService m_UserInterfaceService;

        public UserPagePresenter(IWindow window, IUserPageViewModel viewModel, ConfigurationInfo configurationInfo, IUserInterfaceService userInterfaceService)
            : base(viewModel)
        {
            m_Window = window;
            m_ConfigurationInfo = configurationInfo;
            m_UserInterfaceService = userInterfaceService;

            ViewModel.Username = configurationInfo.Username;
            ViewModel.Password = configurationInfo.Password;

            UpdateIsPasswordValid();
            UpdateIsUsernameValid();
            UpdateIsValid();

            ViewModel.UsernameChanged += ViewModelUsernameChanged;
            ViewModel.PasswordChanged += ViewModelPasswordChanged;
        }

        private void UpdateIsValid()
        {
            ViewModel.IsValid = ViewModel.IsPasswordValid && ViewModel.IsUsernameValid;
        }

        private void ViewModelPasswordChanged(object sender, EventArgs e)
        {
            UpdateIsPasswordValid();
            UpdateIsValid();
        }

        private void UpdateIsPasswordValid()
        {
            ViewModel.IsPasswordValid = !StringHelper.IsNullOrWhiteSpace(ViewModel.Password);
        }

        private void ViewModelUsernameChanged(object sender, EventArgs e)
        {
            UpdateIsUsernameValid();
            UpdateIsValid();
        }

        private void UpdateIsUsernameValid()
        {
            ViewModel.IsUsernameValid = !StringHelper.IsNullOrWhiteSpace(ViewModel.Username);
        }

        protected override bool TryApply()
        {
            bool result = false;
            m_UserInterfaceService.ExecuteActionWithWaitMessage("Verificando usuário", m_Window, () => m_UserInterfaceService.InvokeOnUIThread(() =>
            {
                try
                {
                    SyncService syncService = new SyncService();
                    bool canApply = syncService.Login(ViewModel.Username, ViewModel.Password);
                    result = canApply || m_UserInterfaceService.ShowMessage(
                        "Usuário ou senha inválidos. Deseja continuar com os dados informados?", "Erro de Autenticação",
                        MessageBoxButton.YesNo, MessageBoxImage.Asterisk) == MessageBoxResult.Yes;
                }
                catch (WebException)
                {
                    result = m_UserInterfaceService.ShowMessage(
                            "Não foi possível confirmar usuário e senha. Deseja continuar sem confirmar autenticação?",
                            "Erro de Autenticação", MessageBoxButton.YesNo, MessageBoxImage.Asterisk) ==
                            MessageBoxResult.Yes;
                }
                if (result)
                {
                    m_ConfigurationInfo.SetUserSettings(ViewModel.Username, ViewModel.Password);
                }
            }));
            return result;
        }
    }
}